///
import 'package:flutter/material.dart';

/// 表单组件
/// 参照Element UI的Form控件实现

/// 表单验证状态枚举
enum EFormValidateState {
  /// 初始状态
  initial,
  
  /// 验证成功
  success,
  
  /// 验证失败
  error,
}

/// 表单尺寸枚举
enum EFormSize {
  /// 小型表单
  small,
  
  /// 普通大小表单
  normal,
  
  /// 大型表单
  large,
}

/// 表单布局枚举
enum EFormLayout {
  /// 水平布局
  horizontal,
  
  /// 垂直布局
  vertical,
}

/// 表单验证规则类
class EFormRule {
  /// 创建表单验证规则
  EFormRule({
    required this.validate,
    required this.message,
    this.trigger = const ['blur', 'change'],
  });
  
  /// 验证函数
  final bool Function(String?) validate;
  
  /// 错误信息
  final String message;
  
  /// 触发验证的事件类型
  final List<String> trigger;
}

/// 表单模型类
class EFormModel extends ChangeNotifier {
  /// 表单数据
  final Map<String, dynamic> _fields = {};
  
  /// 表单验证规则
  final Map<String, List<EFormRule>> _rules = {};
  
  /// 验证状态
  final Map<String, EFormValidateState> _validateStates = {};
  
  /// 错误信息
  final Map<String, String> _errorMessages = {};
  
  /// 表单尺寸
  final EFormSize _size;
  
  /// 表单布局
  final EFormLayout _layout;
  
  /// 创建表单模型
  EFormModel({
    Map<String, dynamic>? model,
    Map<String, List<EFormRule>>? rules,
    EFormSize size = EFormSize.normal,
    EFormLayout layout = EFormLayout.horizontal,
  })  : _size = size,
        _layout = layout {
    if (model != null) {
      _fields.addAll(model);
    }
    
    if (rules != null) {
      _rules.addAll(rules);
    }
    
    // 初始化验证状态
    for (final key in _fields.keys) {
      _validateStates[key] = EFormValidateState.initial;
    }
  }
  
  /// 获取表单数据
  Map<String, dynamic> get fields => _fields;
  
  /// 获取表单规则
  Map<String, List<EFormRule>> get rules => _rules;
  
  /// 获取验证状态
  Map<String, EFormValidateState> get validateStates => _validateStates;
  
  /// 获取错误信息
  Map<String, String> get errorMessages => _errorMessages;
  
  /// 获取表单尺寸
  EFormSize get size => _size;
  
  /// 获取表单布局
  EFormLayout get layout => _layout;

  /// 设置字段值
  void setField(String field, dynamic value) {
    _fields[field] = value;
    notifyListeners();
  }
  
  /// 获取字段值
  dynamic getField(String field) {
    return _fields[field];
  }
  
  /// 添加验证规则
  void addRule(String field, List<EFormRule> rules) {
    _rules[field] = rules;
  }

  /// 验证单个字段
  bool validateField(String field, String? value, {String? trigger}) {
    final rules = _rules[field];
    if (rules == null || rules.isEmpty) {
      return true;
    }

    for (final rule in rules) {
      // 检查触发条件
      if (trigger != null && !rule.trigger.contains(trigger)) {
        continue;
      }

      if (!rule.validate(value)) {
        _validateStates[field] = EFormValidateState.error;
        _errorMessages[field] = rule.message;
        notifyListeners();
        return false;
      }
    }

    _validateStates[field] = EFormValidateState.success;
    _errorMessages.remove(field);
    notifyListeners();
    return true;
  }

  /// 验证所有字段
  bool validate() {
    bool isValid = true;
    for (final field in _fields.keys) {
      final value = _fields[field];
      final fieldValid = validateField(field, value?.toString());
      if (!fieldValid) {
        isValid = false;
      }
    }
    notifyListeners();
    return isValid;
  }

  /// 重置表单
  void reset() {
    _fields.clear();
    _validateStates.clear();
    _errorMessages.clear();
    notifyListeners();
  }
  
  /// 清除验证状态
  void clearValidate() {
    _validateStates.forEach((key, _) {
      _validateStates[key] = EFormValidateState.initial;
    });
    _errorMessages.clear();
    notifyListeners();
  }
}

/// 表单组件
class EForm extends StatefulWidget {
  /// 创建表单组件
  const EForm({
    super.key,
    this.model,
    this.rules,
    this.size = EFormSize.normal,
    this.layout = EFormLayout.horizontal,
    this.labelWidth,
    this.labelPosition = 'right',
    this.requiredMark = true,
    this.validateOnRuleChange = true,
    this.onSubmit,
    this.onReset,
    required this.children,
  });
  
  /// 表单数据模型
  final Map<String, dynamic>? model;
  
  /// 表单验证规则
  final Map<String, List<EFormRule>>? rules;
  
  /// 表单尺寸
  final EFormSize size;
  
  /// 表单布局
  final EFormLayout layout;
  
  /// 标签宽度
  final double? labelWidth;
  
  /// 标签位置
  final String labelPosition;
  
  /// 是否显示必填星号
  final bool requiredMark;
  
  /// 规则变化时是否重新验证
  final bool validateOnRuleChange;
  
  /// 表单提交回调
  final VoidCallback? onSubmit;
  
  /// 表单重置回调
  final VoidCallback? onReset;
  
  /// 子部件
  final List<Widget> children;
  
  @override
  State<EForm> createState() => _EFormState();
}

class _EFormState extends State<EForm> {
  /// 表单模型
  late EFormModel _formModel;
  
  @override
  void initState() {
    super.initState();
    _formModel = EFormModel(
      model: widget.model,
      rules: widget.rules,
      size: widget.size,
      layout: widget.layout,
    );
  }
  
  @override
  void didUpdateWidget(covariant EForm oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.model != widget.model ||
        oldWidget.rules != widget.rules ||
        oldWidget.size != widget.size ||
        oldWidget.layout != widget.layout) {
      _formModel = EFormModel(
        model: widget.model,
        rules: widget.rules,
        size: widget.size,
        layout: widget.layout,
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return FormModelProvider(
      model: _formModel,
      child: SizedBox(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: widget.children,
        ),
      ),
    );
  }
}

/// 表单模型提供者
class FormModelProvider extends InheritedNotifier<EFormModel> {
  /// 创建表单模型提供者
  const FormModelProvider({
    super.key,
    required EFormModel model,
    required super.child,
  }) : super(notifier: model);
  
  /// 从BuildContext中获取表单模型
  static EFormModel of(BuildContext context) {
    final FormModelProvider? result = 
        context.dependOnInheritedWidgetOfExactType<FormModelProvider>();
    assert(result != null, 'No FormModelProvider found in context');
    return result!.notifier!;
  }
  
  /// 从BuildContext中获取表单模型（不监听变化）
  static EFormModel? maybeOf(BuildContext context) {
    final FormModelProvider? result = 
        context.getElementForInheritedWidgetOfExactType<FormModelProvider>()?.widget as FormModelProvider?;
    return result?.notifier;
  }
}

/// 表单操作工具类
extension EFormExtension on BuildContext {
  /// 获取表单模型
  EFormModel get eForm => FormModelProvider.of(this);
  
  /// 验证表单
  bool validateForm() {
    return FormModelProvider.of(this).validate();
  }
  
  /// 重置表单
  void resetForm() {
    FormModelProvider.of(this).reset();
  }
  
  /// 清除验证状态
  void clearFormValidate() {
    FormModelProvider.of(this).clearValidate();
  }
  
  /// 获取表单数据
  Map<String, dynamic> getFormData() {
    return FormModelProvider.of(this).fields;
  }
  
  /// 设置表单数据
  void setFormData(Map<String, dynamic> data) {
    final formModel = FormModelProvider.of(this);
    for (final entry in data.entries) {
      formModel.setField(entry.key, entry.value);
    }
  }
}